package com.hedl.practice.diyJava.network_programming.s_email;

import com.hedl.practice.diyJava.network_programming.s_email.utils.Pop3;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import java.io.IOException;

public class Client {
    /**
     * 小结:
     *      使用Java接收Email时，可以用POP3协议或IMAP协议;
     *      使用POP3协议时，需要用Maven引入JavaMail依赖，并确定POP3服务器的域名／端口／是否使用SSL等，然后，调用相关API接收Email。
     *      设置debug模式可以查看通信详细内容，便于排查错误。
     * @param args
     * @throws MessagingException
     * @throws IOException
     */
    public static void main(String[] args) throws MessagingException, IOException {
        Pop3 pop = new Pop3("pop.qq.com", "302572985@qq.com", "snyfqsyfdqnkcadg");
        Folder folder = null;
        Store store = null;
        try {
            store = pop.createSSLStore();
            // 获取收件箱:
            folder = store.getFolder("INBOX");
            // 以读写方式打开:
            folder.open(Folder.READ_WRITE);
            // 打印邮件总数/新邮件数量/未读数量/已删除数量:
            System.out.println("Total messages: " + folder.getMessageCount());
            System.out.println("New messages: " + folder.getNewMessageCount());
            System.out.println("Unread messages: " + folder.getUnreadMessageCount());
            System.out.println("Deleted messages: " + folder.getDeletedMessageCount());
            // 获取每一封邮件:
            Message[] messages = folder.getMessages();
            for (Message message : messages) {
                // 打印每一封邮件:
                pop.printMessage((MimeMessage) message);
            }
        } finally {
            if (folder != null) {
                try {
                    folder.close(true);     //传入true表示删除操作会同步到服务器上（即删除服务器收件箱的邮件）
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
            if (store != null) {
                try {
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
